﻿$(function () {
	$(document).on('click', '.pax, .gax, .dax', function (e) {
		e.preventDefault();
		var ln = $(this);
		var typeReq = ln.hasClass('pax') ? 'post' : 'get';
		$.ajax({
			url: ln.attr('href'),
			dataType: 'json',
			type: typeReq,
			contentType: 'application/json; charset=utf-8'
		}).done(function (ed) {
			receive(ed, ln);
		});
	});

	$(document).on('click', '.close', function (e) {
		e.preventDefault();
		$($(this).attr('target')).hide();
	});

	$(document).on('click', '.remove', function (e) {
		e.preventDefault();
		$($(this).attr('target')).remove();
	});

	$(document).on('submit', 'form', function (e) {
		e.preventDefault();
		/*if (!$(this).valid())
		 return;*/
		$(this).ajaxSubmit({
			success: function (ed) {
				receive(ed, null, null);
			}
		});
	});

	$(window).on('popstate', function (e) {
		if (e.state == "ajax")
			window.location.reload();
		else
			window.history.replaceState("ajax", document.title, window.location.href);
		e.preventDefault();
	});

	function receive(ed, ln) {
		if (ed.redirect) {
			location.assign(ed.redirect);
		}
		$(ed.repl).each(function (i, el) {
			$(el.select).html(el.data);
		});
		if (ed.title && ln && !ln.hasClass('dax')) {
			document.title = ed.title;
			//if (!ln.hasClass('dax'))
			//location.assign(ln.attr('href'));
			window.history.pushState("ajax", document.title, ln.attr('href'));
		}
	}
});